package com.example.commen.other

import android.content.res.Resources
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.DrawableRes
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlin.math.roundToInt

val View.inflater: LayoutInflater
    get() = LayoutInflater.from(context)

fun Int.toPx(resources: Resources): Int {
    return (this * resources.displayMetrics.density).roundToInt()
}

@BindingAdapter("isVisible")
fun isVisible(view: View, isVisible: Boolean?) {
    view.visibility = if (isVisible == true) View.VISIBLE else View.GONE
}


@BindingAdapter("isInvisible")
fun isInvisible(view: View, isInvisible: Boolean?) {
    view.visibility = if (isInvisible == true) View.INVISIBLE else View.VISIBLE
}

@BindingAdapter("setStatusTextColor")
fun setStatusTextColor(view: View, status: String?) {
    var coler = view.context.getColor(com.example.commen.R.color.common_text_color)
    when (status) {
        "0" -> {
            coler = view.context.getColor(com.example.commen.R.color.green_text)
        }

        "1" -> {
            coler = view.context.getColor(com.example.commen.R.color.red_text)
        }

    }
    (view as TextView).setTextColor(coler)
}

@BindingAdapter("android:src")
fun setImageResource(imageView: ImageView, resId: Int?) {
    if (resId == null) return
    imageView.setImageResource(resId)
}

@BindingAdapter("android:src_glide")
fun setGlideImageResource(imageView: ImageView, objects: Any?) {
    if (objects == null) return
    try {
        val requestOptions = RequestOptions()
        requestOptions.placeholder(com.example.commen.R.drawable.errorimg)
        Glide.with(imageView).load(objects).apply(requestOptions).into(imageView)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

@BindingAdapter("android:drawableStart", "android:drawableEnd")
fun setLeftIcon(textView: TextView, @DrawableRes startResId: Int, @DrawableRes endResId: Int) {
    textView.setCompoundDrawablesWithIntrinsicBounds(startResId, 0, endResId, 0)
}
@BindingAdapter( "android:drawableRightd")
fun setRightIcon(textView: TextView, @DrawableRes endResId: Int) {
    textView.setCompoundDrawablesWithIntrinsicBounds(0, 0, endResId, 0)
}